java理解try&catch和错误处理
import java.util.Scanner;
public class Lab4_5 {
public static void main(String[]args) {
Scanner scan= new Scanner(System.in);
int rows=0;
int rowIndex=0, colIndex=0;
boolean choice1= true;
String y="y";
String n="n";
boolean first = true;
while (choice1==true) {
if (first==true) {
first=false;
System.out.println("Do you want to start(Y/N): ");
} else if (first==false) {
System.out.println("Do you want to continue(Y/N): ");
}
String choice2=scan.next();
if (choice2.equals(y)) {
System.out.println("How many rows/columns(5-21)?");
rows=scan.nextInt();
while (rows<5 || rows>21) {
System.out.println("That is either out of range or not an integer, try again! ");
rows=scan.nextInt();
}
System.out.println("What character?");
String choice3=scan.next();
System.out.println(" ");
for (rowIndex=1; rowIndex<=rows; rowIndex++) {
for (colIndex=1; colIndex<=rows; colIndex++) {
if (rowIndex==1 || rowIndex==rows || colIndex==1 || colIndex==rows) {
System.out.print(choice3);
} else {
System.out.print(" ");
}
}
System.out.println();
}
} else if(choice2.equals(n)) {
choice1 = false;
System.out.println("Thank you. Goodbye.");
} else {
System.out.println("Please either enter Y or N.");
}
}
}//end of main
}
代码打印我需要打印的内容,但当它询问要捕获多少行/列时,我还必须在代码中包含一些内容,以捕获我是否输入了整数以外的内容(在下面的部分中)。需要一些帮助,我们还没有做任何关于如何捕获异常的事情,我不知道如何开始
String choice2=scan.next();
if (choice2.equals(y)) {
System.out.println("How many rows/columns(5-21)?");
rows=scan.nextInt();
while (rows<5 || rows>21) {
System.out.println("That is either out of range or not an integer, try again! ");
rows=scan.nextInt();
}
}
# 1 楼答案
您可以创建一个try-catch块,如下所示:
如果您想在代码中实现这一点,我建议您:
有关更多详细信息,请参见here
# 2 楼答案
你需要了解this请调查一下
基本认识是
还有一个finally块,即使出现错误,它也将始终被执行。它是这样使用的
在您的特定情况下,您可以有以下异常(link)
InputMismatchException-如果下一个标记与整数正则表达式不匹配,或超出范围 NoTouchElementException-如果输入用尽 IllegalStateException-如果此扫描仪已关闭
因此,您需要捕获以下异常:
# 3 楼答案